using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace ErkerTech.DeltaScope.View
{
	public class DropDownForm : Form
	{
		private const Container components = null;

		public DropDownForm()
		{
			InitializeComponent();
		}

		public DropDownForm(bool enableAnimation)
		{
			InitializeComponent();

		    if (!enableAnimation) return;
		    Closing += DropDownFormClosingHandler;
		    Load += DropDownFormLoadHandler;
		}

		private Point GetLocation()
		{
			// If we are closing and lost our owner reference, just return the current position...
			if (Owner == null) return Location;

			Point loLocation;
			try
			{
				var lnOwnerWidth = Owner.DisplayRectangle.Width;
				var lnWidth = DisplayRectangle.Width;
				
				if (lnWidth > lnOwnerWidth)
				{
					var loTemp = Owner.PointToScreen(Owner.DisplayRectangle.Location);
					var lnDiff = (lnWidth - lnOwnerWidth) / 2;
					loLocation = new Point(loTemp.X - lnDiff, loTemp.Y);
				}
				else if (lnWidth == lnOwnerWidth)
					loLocation = Owner.PointToScreen(Owner.DisplayRectangle.Location);
				else
				{
					var loTemp = Owner.PointToScreen(Owner.DisplayRectangle.Location);
					var lnDiff = (lnOwnerWidth - lnWidth) / 2;
					loLocation = new Point(loTemp.X + lnDiff, loTemp.Y);
				}
			}
			catch
			{
				//Don't care about the error... just return a valid value...
				loLocation = Location;
			}

			//Return the location...
			return loLocation;
		}
		public void SetLocation()
		{
			Location = GetLocation();
		}

		#region Windows Form Designer generated code
		protected override void Dispose( bool disposing )
		{
			if ( ( disposing ) && (components != null)) components.Dispose();
			base.Dispose( disposing );
		}
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			// 
			// DropDownForm
			// 
			AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			ClientSize = new System.Drawing.Size(424, 173);
			ControlBox = false;
			FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
			MaximizeBox = false;
			MinimizeBox = false;
			Name = "DropDownForm";
			ShowInTaskbar = false;
			SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
			StartPosition = System.Windows.Forms.FormStartPosition.Manual;
		}
		#endregion

	    private void OwnerResizeHandler(object sender, EventArgs e)
		{
			SetLocation();
		}

		private void OwnerMoveHandler(object sender, EventArgs e)
		{
			SetLocation();
		}

		private void DropDownFormLoadHandler(object sender, EventArgs e)
		{
			SetLocation();
			Owner.Move += OwnerMoveHandler;
			Owner.Resize += OwnerResizeHandler;
		}

		private void DropDownFormClosingHandler(object sender, CancelEventArgs e)
		{	
			Owner.Invalidate(true);
		}
	}
}
